package com.xxx.service;

import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import com.alibaba.fastjson.JSON;
import com.xxx.pojo.Content;
import com.xxx.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author George
 * 业务
 */
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
//    解析数据放入 es 索引库中
    public Boolean parseContent(String keywords) throws IOException {
        List<Content> contents = new HtmlParseUtil().parseJD(keywords);
//        把查询到的数据插入到 es 中
        BulkRequest request = new BulkRequest();
        //最大响应时长
        request.timeout("2m");

        for (int i = 0; i < contents.size(); i++) {
//            查看遍历内容
            System.out.println(JSON.toJSONString(contents.get(i)));
            request.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    //    实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword, int pageNo, int PageSize) throws IOException {
        if (pageNo <= 1){
            pageNo = 1;
        }
//        条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(PageSize);
//        精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

//        执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()){
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }



    //    实现搜索并且添加高亮
    public List<Map<String,Object>> searchPageHighlightField(String keyword, int pageNo, int PageSize) throws IOException {
        if (pageNo <= 1){
            pageNo = 1;
        }
//        条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(PageSize);

//        高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高需要高亮的字段
        highlightBuilder.field("title");
//        关闭多个高亮
        highlightBuilder.requireFieldMatch(false);
//        高亮显示颜色设置
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
//        匹配查询
//        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
//        精准查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

//        执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()){

            Map<String, HighlightField> highlightField = hit.getHighlightFields();
//            获取高亮字段
            HighlightField title = highlightField.get("title");
//            原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//            解析高亮的字段，将原来的字段换为我们高亮的字段即可
            if (title != null){
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments){
                    n_title += text;
                }
//                将高亮的字段替换掉原来的内容
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }

}
